package com.bwie.filter;

import com.google.errorprone.annotations.Var;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Mikey
 * @Date: 2025/9/9 10:28
 * @Description:
 **/
@Configuration
public class MyFilter implements GlobalFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${mygateway.rule.path}")
    private String path;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //  拆解白名单
        String[] rulePaths = path.split(",");

        //从请求头中获取请求路径判断是否是白名单
        String requestPath = request.getPath().toString();
        for (String rulePath : rulePaths) {
            if(requestPath.contains(rulePath)){
                //放行
                return chain.filter(exchange);
            }
        }

        //获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            System.out.println("请求头中token不能为空:"+requestPath);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拦截
            return response.setComplete();
        }

        //解密token
        Integer userId = Jwts.parser().setSigningKey("ashujio56785678").parseClaimsJws(token)
                .getBody().get("id", Integer.class);

        //获取redis中存储的token
        String redisToken = redisTemplate.opsForValue().get("token-" + userId);
        if(redisToken==null){
            System.out.println("token已过期:"+requestPath);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拦截
            return response.setComplete();
        }

        //判断token是否一致
        if(!token.equals(redisToken)){
            System.out.println("token不一致:"+requestPath);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拦截
            return response.setComplete();
        }

        //延期放行
        redisTemplate.expire("token-"+userId,15, TimeUnit.MINUTES);

        return chain.filter(exchange);
    }
}
